package com.jiaertangshi.jiaer.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiaertangshi.jiaer.dao.TuserMapper;
import com.jiaertangshi.jiaer.dao.UserInfoMapper;
import com.jiaertangshi.jiaer.dto.Tuser;
import com.jiaertangshi.jiaer.dto.UserInfo;
import com.jiaertangshi.jiaer.tools.HttpClientUtil;

import net.sf.json.JSONObject;

@Service
public class UserService {
	
	
	@Autowired
	TuserMapper  tuserMapper;
	
	@Autowired
	UserInfoMapper     tuserInfoMapper;
	
	public   int    userRegister(Tuser   user){
		int  res =  tuserMapper.insertSelective(user);
		return   res;
	}

	//请求微信接口登录认证
	public JSONObject wxLogin(String js_code, UserInfo userInfo, Tuser tuser) {
	    //		https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code	
		String  url  = "https://api.weixin.qq.com/sns/jscode2session";
		JSONObject params = new   JSONObject();
		url=url+"?appid="+"wxe1519e0302d69f3a"+"&secret="+"627b6e957c13513c85b0992f4d851ada"+"&js_code="+js_code+"&grant_type="+"authorization_code";
//		params.put("appid", "wx973c539e156b34e1");
//		params.put("secret", "6d711ff08df48c90604005dae85a4d30");
//		params.put("js_code", js_code);
//		params.put("grant_type", "authorization_code");
		HttpClientUtil     client =  new  HttpClientUtil();
		JSONObject        js =  	client.doGETSSL(url, url, params, "", "");//请求微信接口登录认证
		JSONObject  myJson = JSONObject.fromObject(js.getString("result"));
		
		String   openid = myJson.getString("openid");//微信用户唯一标识
		Tuser    userOpenid  =   tuserMapper.findUserByOpenid(openid);//判断此用户是否是第一次登陆
		try {
			userOpenid.getOpenid();	
			js.put("userid", userOpenid.getTuserid());
		} catch (Exception e) {//如果是第一次登陆就存储此用户的信息
			System.out.println(js+"js-------");
			tuser.setOpenid(myJson.getString("openid"));
			tuser.setSessionkey(myJson.getString("session_key"));
			tuser.setUpdatedAt(new  Date());
			int  res =  tuserMapper.insertSelectiveMy(tuser);
			if(res==1){
				userInfo.setUserid(tuser.getTuserid());
				userInfo.setUpdatedAt(new  Date());
				tuserInfoMapper.insertSelective(userInfo);
				js.put("userid", tuser.getTuserid());
			}
		}
		return js;
	}
	

}
